﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data.Linq;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.WebUI
{
	public class VoteRsContent : VoteContent
	{
		private LoadedValue<int> loadedVoteListId;
		public virtual int VoteListId
		{
			get
			{
				if (loadedVoteListId.Loader == null)
					loadedVoteListId.Loader = () => (int)ViewState["VoteListId"];
				return loadedVoteListId.Value;
			}
			set
			{
				if (loadedVoteListId.Setter == null)
					loadedVoteListId.Setter = v => ViewState["VoteListId"] = v;
				loadedVoteListId.Value = value;
			}
		}

		public override int VoteId
		{
			get
			{
				return VoteListId;
			}
		}

		protected override void RewriteMeta()
		{
			//base.RewriteMeta();
		}

		private LoadedValue<string> loadedClassCode;
		public virtual string ClassCode
		{
			get
			{
				if (loadedClassCode.Loader == null)
					loadedClassCode.Loader = () => (string)ViewState["ClassCode"];
				return loadedClassCode.Value;
			}
			set
			{
				if (loadedClassCode.Setter == null)
					loadedClassCode.Setter = v => ViewState["ClassCode"] = v;
				loadedClassCode.Value = value;
			}
		}

		public virtual string DivHideClass
		{
			get
			{
				if (!string.IsNullOrEmpty(ClassCode))
					return "hideMe";
				return "";
			}
		}

		private LoadedValue<string> loadedTitleClass;
		public virtual string TitleClass
		{
			get
			{
				if (loadedTitleClass.Loader == null)
					loadedTitleClass.Loader = () => (string)ViewState["TitleClass"];
				return loadedTitleClass.Value;
			}
			set
			{
				if (loadedTitleClass.Setter == null)
					loadedTitleClass.Setter = v => ViewState["TitleClass"] = value;
				loadedTitleClass.Value = value;
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			Hxsoft.AppV1.Page page = this.Page as Hxsoft.AppV1.Page;
			if (page != null)
				page.RegisterHeadIncludeFile(ApplicationConfiguration.VoteFolderUrl + "/C.css", IncludeFileType.CSS);

			base.OnPreRender(e);
		}

		private LoadedValue<string> loadedActionUrl;
		public virtual string ActionUrl
		{
			get
			{
				if (loadedActionUrl.Loader == null)
					loadedActionUrl.Loader = () => (string)ViewState["ActionUrl"];
				return loadedActionUrl.Value;
			}
			set
			{
				if (loadedActionUrl.Setter == null)
					loadedActionUrl.Setter = v => ViewState["ActionUrl"] = v;
				loadedActionUrl.Value = value;
			}
		}

		private LoadedValue<string> loadedChackActionFunction;
		public virtual string ChackActionFunction
		{
			get {
				if (loadedChackActionFunction.Loader == null)
					loadedChackActionFunction.Loader = () => (string)ViewState["ChackActionFunction"];
				return loadedChackActionFunction.Value;
			}
			set {
				if (loadedChackActionFunction.Setter == null)
					loadedChackActionFunction.Setter = v => ViewState["ChackActionFunction"] = v;
				loadedChackActionFunction.Value = value;
			}
		}

		private const string VoteHistoryKey = "VoteHistory";
		protected virtual void Process()
		{
			var HistoryKey = string.Format("{0}_{1}_{2}", VoteHistoryKey, VoteId, DateTime.Today.ToString("yyyy_MM_dd"));
			var cookie = HttpContext.Current.Request.Cookies[HistoryKey];
			int[] cookieValues = null;
			if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
			{
				cookieValues = Hxsoft.StringExtensions.Decompound<int>(cookie.Value, ",", StringSplitOptions.RemoveEmptyEntries);
				if (cookieValues != null && cookieValues.Contains(VoteDetail.VoteId))
					return;
			}
			cookie = new HttpCookie(HistoryKey);
			// 进行调查
			int? voteId = IntExtensions.ParseOrNull(Request.Form["VoteId"]);
			if (voteId.HasValue && VoteDetail.VoteId == voteId.Value)
			{
				string strVoteItem = Request.Form["VoteItem"];
				int[] voteItems = Hxsoft.StringExtensions.Decompound<int>(strVoteItem, ",", StringSplitOptions.RemoveEmptyEntries);
				string userDefinedContent = Request.Form["UserDefinedContent"];
				if ((voteItems != null && voteItems.Length > 0) || !string.IsNullOrEmpty(userDefinedContent))
				{
					// 需要填写联系信息表单
					string name = null;
					string telephone = null;
					if (VoteDetail.NeedContactInfo)
					{
						name = Request.Form["Name"];
						telephone = Request.Form["Telephone"];						
					}

					VoteResult result = new VoteResult();
					result.Ip = Request.UserHostAddress;
					result.SelectedIndexs = voteItems;
					result.UserDefinedContent = userDefinedContent;
					result.VoteId = voteId.Value;
					result.Name = name;
					result.Telephone = telephone;
					result = Votes.Vote(result);

					List<int> cookieValueList = new List<int>();
					if (cookieValues != null) cookieValueList.AddRange(cookieValues);
					cookieValueList.Add(voteId.Value);
					cookie.Value = Hxsoft.StringExtensions.Compound<int>(cookieValueList, ",");
					cookie.Expires = DateTime.Now.AddDays(1);
					HttpContext.Current.Response.Cookies.Add(cookie);
				}
			}
		}

		public virtual string VoteViewHtml
		{
			get
			{
				Process();
				var voteDetail = Votes.GetItem(VoteId);

				StringBuilder html = new StringBuilder();

				html.AppendLine(string.Format(@"<form id=""{0}"" method=""post"" action=""{1}"">", this.ClientID, string.Format("{0}?VoteId={1}&Code={2}", ActionUrl, VoteId, ClassCode)));
				html.AppendLine(string.Format(@"<input type=""hidden"" id=""hdVoteId_{0}"" name=""VoteId"" value=""{0}"" />", VoteId));
				html.AppendLine(string.Format(@"<input type=""hidden"" id=""hdVoteItem_{0}"" name=""VoteItem""/>", VoteId));
				html.AppendLine(@"<table class=""VoteTable"">");

				for (int i = 1; i <= voteDetail.VoteItemList.Count; i++)
				{
					VoteItem item = voteDetail.VoteItemList[i - 1];
					double percent = (voteDetail.VoteCount == 0 ? 0 : (double)item.VoteCount / voteDetail.VoteCount * 100);
					percent = Math.Round(percent, 2);

					html.AppendLine(@"<tr>");
					html.AppendLine(string.Format(@"<td class=""VoteRatio"" id=""VoteRatio_{0}_{1}"" title=""{2}%""><span class=""percent_bg""><span id=""percent_{0}_{1}""  style=""width:{2}%"" class=""percent""><span class=""percentText"">{3}</span>&nbsp;</span></span></td>", VoteId, i, percent, item.OptionTitle));
					html.AppendLine(string.Format(@"<td class=""Button""><input class=""submit submit_{3}"" type=""submit"" value=""投票"" onclick=""javascript:{1}({0},{2})"" /></td>", i, ChackActionFunction, VoteId, TitleClass));
					html.AppendLine(string.Format(@"<td class=""VoteCount"" id=""VoteItemResult_{0}_{1}"" >" + item.VoteCount + @"</td>", VoteId, i));
					html.AppendLine(@"</tr>");
				}

				html.AppendLine("</table></form>");

				return html.ToString();
			}
		}
	}
}
